package com.hhit.collaborative_learning.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.hhit.collaborative_learning.dao.BlogDao;
import com.hhit.collaborative_learning.utils.DateUtil;
import com.hhit.collaborative_learning.utils.StringUtil;
import com.hhit.collaborative_learning.utils.Utils;
import com.mysql.jdbc.StringUtils;

public class BlogDaoImpl implements BlogDao {

	@Override
	public ResultSet queryforSearch(Connection con, int start, int end,
			String find, String order, String sort) {
		// TODO Auto-generated method stub
		String sql = "SELECT b.blogId,b.blogName,b.readNum,b.userId,u.userNickName,b.time FROM collaborative_learning.blog as b left  join  collaborative_learning.user as u on u.userId=b.userId where b.state=1 and b.isDelete=0";
		if (!StringUtils.isNullOrEmpty(find)) {
			sql += " and (b.blogName like '%" + find
					+ "%' or u.userNickName like '%" + find + "%' or b.tag like '%"+find+"%' or b.blogDesc like '%"+find+"%' or b.category like '%"+find+"%' or b.category_CN like '%"+find+"%') ";
		}
		if (!StringUtils.isNullOrEmpty(sort)) {
			sql += " order by " + sort + " ";
			if (order != null) {
				sql += " " + order;
			}
		}
//		if (end != 0 && start < end) {
			sql += " limit " + start + "," + end;
//		}
		PreparedStatement prs;
		try {
			prs = con.prepareStatement(sql);
			return prs.executeQuery();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("非法请求：" + sql);
			return null;
		}
	}

	@Override
	public int getcount(Connection con, String find) {
		// TODO Auto-generated method stub
		int num = 0;
		String sql = "select count(*) from blog b,user u";
		if (!StringUtils.isNullOrEmpty(find)) {
			sql += " where " + find + " ";
		}
		try {
			PreparedStatement prs = con.prepareStatement(sql);
			ResultSet res = prs.executeQuery();
			if (res.next()) {
				num = res.getInt(1);
			}
		} catch (SQLException ex) {
			ex.printStackTrace();
		}
		return num;
	}

}
